<?php
/**
 * Created by PhpStorm.
 * User: yanji
 * Date: 2018/3/31
 * Time: 9:20
 */

namespace Admin\Controller;

use think\Controller;
class GWController extends Controller
{
    public function index()
    {
        session('orders', null);
        session('successTimes', null);
        session('overdueTimes', null);
        if (!file_get_contents('./Public/Uploads/GW')) {
            mkdir('./Public/Uploads/GW');
        }
        if (I('request.status') == 0) {
            $this -> assign('status', 0);
            $this->display('Stock/gw_list_success');
        } else if (I('request.status') == 1) {
            $this -> assign('status', 1);
            $this->display('Stock/gw_list_overdue');
        } else if (I('request.status') == 2) {
            $this->display('Stock/gw_list_s');
        } else if (I('request.status') == 3) {
            $this->display('Stock/order_list');
        } else if (I('request.status') == 4) {
            $this->display('Channel/channel_list_success');
        }

    }

    public function twoCascades()
    {
        $city_db = M('city');
        $province = $city_db -> where('pid=0') -> select();
        $city_res = $city_db -> where('pid <> 0') -> select();
        $city = [];
        $city1 = [];
        foreach ($province as $k => $v) {
            $result = [];
            $city[$province[$k]['id']] = $province[$k]['name'];
            foreach ($city_res as $key => $value) {
                if ($province[$k]['id'] == $city_res[$key]['pid']) {
                    $result[$city_res[$key]['id']] = $city_res[$key]['name'];
                }
            }
            $city1[] = $result;
        }
        $this -> ajaxReturn([$city, $city1], 'JSON');
    }

    public function fourCascades()
    {
        $city_db = M('city');
        $admin_db = M('admin');
        $way_db = M('wayuser');

        $province_res = $city_db -> where(array('pid' => 0)) -> select();
        $city_res = $city_db -> where('pid <> 0') -> select();
        $ways_res = $way_db -> where('waynum <> 0') -> select();
//        $where = "id in (".implode(',', array_column($ways_res, 'admin_id')).") and position = 1 and test_sign <> 1";
        $where = "position = 1 and test_sign <> 1";
        $admins = $admin_db -> where($where) -> select();

        $province = [];
        $citys = [];
        $gwusernum = [];
        $waynums = [];
        foreach ($province_res as $k => $v) {
            $city = [];
            $gws = [];
            $wayss = [];
            $province[$province_res[$k]['id']] =$province_res[$k]['name'];
            foreach ($city_res as $key => $value) {
                if ($province_res[$k]['id'] == $city_res[$key]['pid']) {
                    $city[$city_res[$key]['id']] =  $city_res[$key]['name'];
                }
            }
            foreach ($city as $key => $value) {
                $gw = [];
                $ways = [];
                foreach ($admins as $i => $j) {
                    if ($key == $admins[$i]['cityid']) {
                        $gw[$admins[$i]['id']] = $admins[$i]['usernum'];
                    }

                }
                foreach ($gw as $i => $j) {
                    $way = [];
                    foreach ($ways_res as $d => $z) {
                        if ($i == $ways_res[$d]['admin_id']) {
                            $way[] = $ways_res[$d]['waynum'];
                        }
                    }
                    $ways[] = $way;
                }
                $gws[] = $gw;
                $wayss[] = $ways;
            }

            $citys[] = $city;
            $gwusernum[] = $gws;
            $waynums[] = $wayss;
        }
        $this -> ajaxReturn(['province' => $province, 'city' => $citys, 'gws' => $gwusernum, 'waynums' => $waynums], 'JSON');
    }

    public function getAllGwPersonnelList()
    {
        $status = I('request.status');
        $usernum = I('request.usernum');
        $gwStatus = I('request.gwStatus');
        $province = I('request.province');
        $city = I('request.city');
        $successTimes = I('request.successMonths');//时间
        $overdueTimes = I('request.overdueMonths');//时间
        $success_l = I('request.successl');//过单率
        $successTag = I('request.successtag');
        $overduel = I('request.overduel');//过单率
        $overdueTag = I('request.overduetag');

        $admin_db = M('admin');
        $order_db = M('order');
        $city_db = M('city');
        $order_operation_db = M('order_operation');
        $order_month_pay_db = M('order_month_pay');
        $adminWhere = '';
        if ($usernum && $status == 0) {
            $adminWhere = "usernum="."'".$usernum."'"." and position=1 and test_sign <> 1";
            $gws = $admin_db -> where($adminWhere) -> select();
            if (!$gws) {
                $this -> ajaxReturn(['error' => 1, 'msg' => []], 'JSON');
            }
        } else {
            if (($gwStatus == 0 || $gwStatus == 1) && $gwStatus != '') {
                $adminWhere .= 'status='.$gwStatus.' and ';
            }
            if ($province && $city) {
                $adminWhere .= ' provinceid='.$province.' and cityid='.$city.' and position=1 and test_sign <> 1';
            } else if ($province) {
                $adminWhere .= ' provinceid='.$province.' and position=1 and test_sign <> 1';
            } else if ($adminWhere != '') {
                $adminWhere .= 'status='.$gwStatus.' and position=1 and test_sign <> 1';
            }else {
                $adminWhere .= 'position=1 and test_sign <> 1';
            }
            $gws = $admin_db -> where($adminWhere) -> select();
            if (!$gws) {
                $this -> ajaxReturn(['error' => '', 'msg' => []], 'JSON');
            }
        }

        //查询城市经理跟省总
        $sz = $admin_db -> where('position=4 or position=3') -> select();
        //查询所有的订单
        $orders = $order_db -> select();
        //查询所有的订单记录
        $orderopration = $order_operation_db -> select();
        //查询所有订单分期
        $order_month_pay = $order_month_pay_db -> select();
        //查询所有城市
        $city = $city_db -> select();
        if (count($successTimes) != 2 || !$successTimes) {
//            $curry = date('Y', time());
//            $currm = date('m', time());
//            $y = date('Y', 1517363215);
//            $m = date('m', 1517363215);
//            $curr = ($curry * 12 + $currm) - ($y * 12 + $m);
//            $successTimes  = [1, $curr+1];
            $successTimes  = [1, 12];
        }
        if (count($overdueTimes) != 2 || !$overdueTimes) {
//            $curry = date('Y', time());
//            $currm = date('m', time());
//            $y = date('Y', 1517363215);
//            $m = date('m', 1517363215);
//            $curr = ($curry * 12 + $currm) - ($y * 12 + $m);
//            $overdueTimes  = [1, $curr+1];
            $overdueTimes  = [1, 12];
        }
        $data = $this -> getAllGwPersonnel($orders, $orderopration, $order_month_pay, $gws, $sz, $city, $successTimes, $overdueTimes, $success_l, $overduel, $successTag, $overdueTag, $usernum);
        $orderM = D('order');
        session('successTimes', base64_encode(json_encode($orderM -> getDates($successTimes[0], $successTimes[1]))));
        session('overdueTimes', base64_encode(json_encode($orderM -> getDates($overdueTimes[0], $overdueTimes[1]))));
        session('orders', base64_encode(json_encode($data)));
        $this -> ajaxReturn(['error' => '', 'msg' => $data], 'JSON');
    }

    public function exportToExcelAllPersonnel()
    {
        $status = I('request.status');
        $filterIndexs = I('request.filterIndexs');
        $admin_db = M('admin');
        $order_db = M('order');
        $city_db = M('city');
        $order_operation_db = M('order_operation');
        $order_month_pay_db = M('order_month_pay');

        if ($status != 5) {
            $orderM = D('order');
            $times = $this -> get_d_m($status);
            $time = strtotime($times[0]);
            $arr = explode('-', $times[count($times) - 1]);
            $time1 = strtotime($orderM -> get_y_m_d($arr[0], $arr[1]));
            //查询所有的GW
            $gws = $admin_db -> where('position = 1 and test_sign <> 1') -> select();
            //查询所有的城市经理和省总
            $sz = $admin_db -> where('(position = 3 or position = 4) and test_sign <> 1') -> select();
            //订单记录
            $usernums = "usernum in (".implode(',', array_column($gws, 'usernum')).") and status = 0";
            $order_operaiton = $order_operation_db -> where($usernums) -> select();
            //查询订单
            $orderids = "orderid in (".implode(',', array_column($order_operaiton, 'orderid')).")";
            $orders = $order_db -> where($orderids) -> select();
            //查询分期
            $order_month_pay = $order_month_pay_db -> where($orderids) -> select();
            //查询城市
            $city = $city_db -> select();
            $data = $this -> getAllGwPersonnel($orders, $order_operaiton, $order_month_pay, $gws, $sz, $city, $times, $times, [0,100], [0,100], [],[],null, true);
        } else {
            $data = json_decode(base64_decode(session('orders')), true);
        }
        $titles = [
            '序号',
            '当前状态',
            '入职时间',
            'GW姓名',
            'GW岗位号',
            '城市',
            'CS岗位号',
            '省份',
            'SZ岗位号'
        ];
        if ($status == 5) {
            $times = json_decode(base64_decode(session('successTimes')),true);
        }
        $success = true;
        foreach ($times as $k => $v) {
            if ($success) {
                $orderTotalCount = '总过单数';
                $orderTotalRatio = '总过单比';
                $orderTotalRate = '总过单率';
                array_push($titles, $orderTotalCount);
                array_push($titles, $orderTotalRatio);
                array_push($titles, $orderTotalRate);
                $success = false;
            }
            if ($status == 5) {
                if ($k == 0) {
                    $month = '当月';
                } else if ($k == 1) {
                    $month = '上月';
                } else {
                    $month = '第'.($k+1).'月';
                }
                $orderCount = $month.'过单数';
                $orderRatio = $month.'过单比';
                $orderRate = $month.'过单率';
            } else {
                $orderCount = $times[$k].'月过单数';
                $orderRatio = $times[$k].'月过单比';
                $orderRate = $times[$k].'月过单率';
            }
            array_push($titles, $orderCount);
            array_push($titles, $orderRatio);
            array_push($titles, $orderRate);
        }
        if ($status == 5) {
            $times = json_decode(base64_decode(session('overdueTimes')),true);
        }
        $overdue = true;
        foreach ($times as $k => $v) {
            if ($overdue) {
                $orderTotalCount = '总逾期数';
                $orderTotalRatio = '总逾期比';
                $orderTotalRate = '总逾期率';
                array_push($titles, $orderTotalCount);
                array_push($titles, $orderTotalRatio);
                array_push($titles, $orderTotalRate);
                $overdue = false;
            }
            if ($status == 5) {
                if ($k == 0) {
                    $month = '当月';
                } else if ($k == 1) {
                    $month = '上月';
                } else {
                    $month = '第'.($k+1).'月';
                }
                $orderCount = $month.'逾期数';
                $orderRatio = $month.'逾期比';
                $orderRate = $month.'逾期率';
            } else {
                $orderCount = $times[$k].'月逾期数';
                $orderRatio = $times[$k].'月逾期比';
                $orderRate = $times[$k].'月逾期率';
            }
            array_push($titles, $orderCount);
            array_push($titles, $orderRatio);
            array_push($titles, $orderRate);
        }
        //添加数据
        $results = [];
        foreach ($data as $k => $v) {
            $gwStatus = '正常'; $result = [];
            if ($data[$k]['status'] == 1) $gwStatus = '禁用';
            $result[] = $k+1;
            $result[] = $gwStatus;
            $result[] = $data[$k]['time'];
            $result[] = $data[$k]['gwname'];
            $result[] = $data[$k]['gwusernum'];
            $result[] = $data[$k]['city'];
            $result[] = $data[$k]['csusernum'];
            $result[] = $data[$k]['province'];
            $result[] = $data[$k]['szusernum'];
            $successOrders = $data[$k]['successOrders'];
            foreach ($successOrders as $key => $v) {
                if ($key == 0) {
                    $result[] = $successOrders[$key]['orderTotalCount'];
                    $result[] = $successOrders[$key]['orderTotalRatio'];
                    $result[] = round($successOrders[$key]['orderTotalRate'], 2).'%';
                } else {
                    $result[] = $successOrders[$key]['orderCount'];
                    $result[] = $successOrders[$key]['orderRatio'];
                    $result[] = round($successOrders[$key]['orderRate'], 2).'%';
                }
            }
            $overdueOrders = $data[$k]['overdueOrders'];
            foreach ($overdueOrders as $key => $v) {
                if ($key == 0) {
                    $result[] = $overdueOrders[$key]['orderTotalCount'];
                    $result[] = $overdueOrders[$key]['orderTotalRatio'];
                    $result[] = round($overdueOrders[$key]['orderTotalRate'], 2).'%';
                } else {
                    $result[] = $overdueOrders[$key]['orderCount'];
                    $result[] = $overdueOrders[$key]['orderRatio'];
                    $result[] = round($overdueOrders[$key]['orderRate'], 2).'%';
                }
            }
            $results[] = $result;
        }
        if ($status == 5 && count($filterIndexs) > 1) {
            foreach ($titles as $k => $v) {
                if (!in_array($k.'', $filterIndexs)) {
                    unset($titles[$k]);
                }
            }
            foreach ($results as $key => $value) {
                foreach ($value as $k => $v) {
                    if (!in_array($k.'', $filterIndexs)) {
                        unset($results[$key][$k]);
                    }
                }
            }
        }
        $_savePath = ExportExcelTable($titles, $results, 'sheet', time(),'./Public/Uploads/GW/');
        $path = 'http://'.$_SERVER['SERVER_NAME'].substr($_savePath, 1, strlen($_savePath));
        $this -> ajaxReturn(['path' => $path], 'JSON');
    }

    public function getAllGwPersonnel($orders, $orderopration, $order_month_pay, $gws, $sz, $city, $successTimes, $overdueTimes, $success_l, $overduel, $successTag = [],  $overdueTag = [], $usernum = null, $istimes = false)
    {
        $successOrders = $this -> getSuccessGwOrder($orders, $orderopration);
        $overdueOrders = $this -> getOverudeGwOrder($order_month_pay, $orderopration);
        $data = [];$s = 0; $orderM = D('order');
        foreach ($gws as $k => $v) {
            $result = [];
            $result2 = [];
            foreach ($successOrders as $key => $value) {
                //相等取出订单放入另外一个数组中
                if ($gws[$k]['usernum'] == $successOrders[$key]['usernum']) {
                    $result[] = $successOrders[$key];
                }
            }
            foreach ($overdueOrders as $key => $value) {
                if ($gws[$k]['usernum'] == $overdueOrders[$key]['usernum']) {
                    $result2[] = $overdueOrders[$key];
                }
            }
            //根据订单和时间获取过单数据
            $result = $orderM -> getSuccessOrder($result, $successTimes, $istimes);
            $result2 = $orderM -> getOverdueOrder($result2, $orders, $overdueTimes, $istimes);
            //取出城市经理的usernum和省总的usernum
            foreach ($sz as $key => $value) {
                if ($gws[$k]['pid'] == $sz[$key]['id']) {
                    $gws[$k]['csusernum'] = $sz[$key]['usernum'];
                }
                if ($sz[$key]['position'] == 4 && $gws[$k]['provinceid'] == $sz[$key]['provinceid']) {
                    $gws[$k]['szusernum'] = $sz[$key]['usernum'];
                }
            }
            //取出GW所属城市
            foreach ($city as $key => $value) {
                if ($gws[$k]['provinceid'] == $city[$key]['id']) {
                    $gws[$k]['province'] = $city[$key]['name'];
                }
                if ($gws[$k]['cityid'] == $city[$key]['id']) {
                    $gws[$k]['city'] = $city[$key]['name'];
                }
            }
            $successRate = false;
            foreach ($result as $key => $value) {
                $r = $result[$key];
                if (count($success_l) == 2 &&  $r['orderTotalRate'] >= $success_l[0] && $r['orderTotalRate'] <= $success_l[1]) {
                    $successRate = true;
                }
                if (count($success_l) == 2 &&  $r['orderRate'] >= $success_l[0] && $r['orderRate'] <= $success_l[1]) {
                    $successRate = true;
                }
                if (count($successTag) == 2 &&  $r['orderTotalRate'] >= $successTag[0] && $r['orderTotalRate'] <= $successTag[1]) {
                    $result2[$key]['tag'] = true;
                }
                if (count($successTag) == 2 &&  $r['orderRate'] >= $successTag[0] && $r['orderRate'] <= $successTag[1]) {
                    $result[$key]['tag'] = true;
                }
            }
            $overdueRate = false;
            foreach ($result2 as $key => $value) {
                $r = $result2[$key];
                if (count($overduel) == 2 &&  $r['orderTotalRate'] >= $overduel[0] && $r['orderTotalRate'] <= $overduel[1]) {
                    $overdueRate = true;
                }
                if (count($overduel) == 2 &&  $r['orderRate'] >= $overduel[0] && $r['orderRate'] <= $overduel[1]) {
                    $overdueRate = true;
                }
                if (count($overdueTag) == 2 &&  $r['orderTotalRate'] >= $overdueTag[0] && $r['orderTotalRate'] <= $overdueTag[1]) {
                    $result2[$key]['tag'] = true;
                }
                if (count($overdueTag) == 2 &&  $r['orderRate'] >= $overdueTag[0] && $r['orderRate'] <= $overdueTag[1]) {
                    $result2[$key]['tag'] = true;
                }
            }
            if (!$successRate && !$overdueRate && !$usernum) continue;
            $res = [];
            $res['successOrders'] = [];
            $res['overdueOrders'] = [];
            if ($successRate || $usernum) {
                $res['successOrders'] = $result;
            }
            if ($overdueRate || $usernum) {
                $res['overdueOrders'] = $result2;
            }
            $res['status'] = $gws[$k]['status'];
            $res['time'] = date('Y-m-d', $gws[$k]['insert_time']);
            $res['gwname'] = $gws[$k]['name'];
            $res['gwusernum'] = $gws[$k]['usernum'];
            $res['csusernum'] = $gws[$k]['csusernum'];
            $res['szusernum'] = $gws[$k]['szusernum'];
            $res['province'] = $gws[$k]['province'];
            $res['city'] = $gws[$k]['city'];
            $res['successTimes'] = $successTimes;
            $res['overdueTimes'] = $overdueTimes;
            $data[$s] = $res;
            $s ++;
        }
        return $data;
    }

    public function getSuccessGwOrder($orders, $orderopration)
    {
        //向所有订单中添加GW的usernum
        foreach ($orders as $k => $v) {
            foreach ($orderopration as $key => $value) {
                if ($orders[$k]['orderid'] == $orderopration[$key]['orderid'] && $orderopration[$key]['status'] == 0) {
                    $orders[$k]['usernum'] = $orderopration[$key]['usernum'];
                }
                if ($orders[$k]['orderid'] == $orderopration[$key]['orderid'] &&
                    ($orderopration[$key]['status'] == 2 || $orderopration[$key]['status'] == -1)) {
                    $orders[$k]['success_time'] = $orderopration[$key]['create_time'];
                }
            }
        }
        return $orders;
    }

    public function getOverudeGwOrder($order_month_pay, $order_operation)
    {
        //向所有订单中添加GW的usernum
        foreach ($order_month_pay as $k => $v) {
            foreach ($order_operation as $key => $value) {
                if ($order_month_pay[$k]['orderid'] == $order_operation[$key]['orderid'] &&
                    $order_operation[$key]['status'] == 0) {
                    $order_month_pay[$k]['usernum'] = $order_operation[$key]['usernum'];
                }
            }
        }
        return $order_month_pay;
    }

    public function gwPersonnelList()
    {
        $usernum = I('request.usernum');
        $status = I('request.status');
        $gwStatus = I('request.gwStatus');
        $province = I('request.province');
        $city = I('request.city');
        $times = I('request.times');//时间
        $rates = I('request.rates');//过单率
        $tags = I('request.tags');
        $msg = I('request.msg');
        $admin_db = M('admin');
        $order_db = M('order');
        $city_db = M('city');
        $order_operation_db = M('order_operation');
//        $order_month_pay_db = M('order_month_pay');
        $adminWhere = '';
        if ($usernum && $usernum != '' && $status == 0) {
            $adminWhere = "usernum="."'".$usernum."'"." and position=1 and test_sign <> 1";
            $gws = $admin_db -> where($adminWhere) -> select();
            if (!$gws) {
                $this -> ajaxReturn(['error' => 1, 'msg' => []], 'JSON');
            }
        } else {
            if (($gwStatus == '0' || $gwStatus == '1') && $gwStatus != '') {
                $adminWhere .= 'status='.$gwStatus.' and ';
            }
            if ($province && $city) {
                $adminWhere .= ' provinceid='.$province.' and cityid='.$city.' and position=1 and test_sign <> 1';
            } else if ($province) {
                $adminWhere .= ' provinceid='.$province.' and position=1 and test_sign <> 1';
            } else if ($adminWhere != '') {
                $adminWhere .= 'status='.$gwStatus.' and position=1 and test_sign <> 1';
            }else {
                $adminWhere .= 'position=1 and test_sign <> 1';
            }
            $gws = $admin_db -> where($adminWhere) -> select();
            if (!$gws) {
                $this -> ajaxReturn(['error' => '', 'msg' => []], 'JSON');
            }
        }

        //查询城市经理跟省总
        $sz = $admin_db -> where('(position=4 or position=3) and test_sign <> 1') -> select();
        //查询所有的订单
        $orders = $order_db -> select();
        //查询所有的订单记录
        $orderopration = $order_operation_db -> select();
        //查询所有城市
        $city = $city_db -> select();
        if (count($times) != 2 || !$times) {
//            $curry = date('Y', time());
//            $currm = date('m', time());
//            $y = date('Y', 1517363215);
//            $m = date('m', 1517363215);
//            $curr = ($curry * 12 + $currm) - ($y * 12 + $m);
//            $times = [1, $curr + 1];
            $times = [1, 12];
        }
        $data = $this -> getGwPersonnelInfo($msg, $orders, $orderopration, $gws, $sz, $city, $times, $rates, $tags);
        $orderM = D('order');
        session('msg', $msg);
        session('successTimes', base64_encode(json_encode($orderM -> getDates($times[0], $times[1]))));
        session('orders', base64_encode(json_encode($data)));
        $this -> ajaxReturn(['error' => '', 'msg' => $data], 'JSON');
    }

    public function exportToExcelGwPersonnel()
    {
        $status = I('request.status');
        $msg = I('request.msg');
        $filterIndexs = I('request.filterIndexs');
        if ($status != 5) {
            $admin_db = M('admin');
            $city_db = M('city');
            $order_db = M('order');
            $order_operation_db = M('order_operation');
            //查询所有GW
            $gws = $admin_db -> where('position=1 and test_sign <> 1') -> select();
            //查询所有的省总 查询所有城市经理
            $sz = $admin_db -> where('(position=4 or position=3) and test_sign <> 1') -> select();
            //查询所有城市
            $city = $city_db -> select();
            //查询订单
            $orderM = D('order');
            //获取导出时间
            $times = $this -> get_d_m($status);
            $time = strtotime($times[0].'-1');
            $arr = explode('-', $times[count($times)-1]);
            $time1 = strtotime($orderM -> get_y_m_d($arr[0], $arr[1]));
            //根据时间查询所有的订单
            $orderWhere = "create_time >=".$time.' and create_time <='.$time1;
            $orders = $order_db -> where($orderWhere) -> select();
            //根据订单ID查询订单记录
            $operationWhere = "orderid in (".implode(',', array_column($orders, 'orderid')).")";
            $order_operation = $order_operation_db -> where($operationWhere) -> select();
            //获取所有的GW信息
            $data = $this -> getGwPersonnelInfo($msg, $orders, $order_operation, $gws, $sz, $city, $times, [0,100],[], true);
        } else {
            $msg = session('msg');
            $times = json_decode(base64_decode(session('successTimes')), true);
            $data = json_decode(base64_decode(session('orders')), true);
        }
        if ($msg == 'success') {
            $totalCount = '总过单数';
            $totalRaio = '总过单比';
            $totalRate = '总过单率';
        } else if ($msg == 'overdue') {
            $totalCount = '总逾期数';
            $totalRaio = '总逾期比';
            $totalRate = '总逾期率';
        }
        $titles = array(
            '序号',
            '当前状态',
            '入职时间',
            'GW姓名',
            'GW岗位号',
            'CS岗位号',
            'SZ岗位号',
            '城市',
            '省份',
            $totalCount,
            $totalRaio,
            $totalRate,
        );
        foreach ($times as $k => $v) {
            if ($status != 5) {
                if ($msg == 'success') {
                    $month1 = $v.'月过单数';
                    $month2 = $v.'月过单比';
                    $month3 = $v.'月过单率';
                } else if ($msg == 'overdue') {
                    $month1 = $v.'月逾期数';
                    $month2 = $v.'月逾期比';
                    $month3 = $v.'月逾期率';
                }
            } else {
                if ($k == 0) {
                    $month = '当月';
                } else if ($k == 1) {
                    $month = '上月';
                } else {
                    $month = '第'.($k+1).'月';
                }
                if ($msg == 'success') {
                    $month1 = $month.'过单数';
                    $month2 = $month.'过单比';
                    $month3 = $month.'过单率';
                } else if ($msg == 'overdue') {
                    $month1 = $month.'逾期数';
                    $month2 = $month.'逾期比';
                    $month3 = $month.'逾期率';
                }
            }
            array_push($titles, $month1);
            array_push($titles, $month2);
            array_push($titles, $month3);
        }
        $results = [];
        foreach ($data as $k => $v) {
            $gwStatus = '正常'; $result = [];
            if ($data[$k]['status'] == 1) $gwStatus = '禁用';
            $result[] = $k+1;
            $result[] = $gwStatus;
            $result[] = $data[$k]['time'];
            $result[] = $data[$k]['gwname'];
            $result[] = $data[$k]['gwusernum'];
            $result[] = $data[$k]['city'];
            $result[] = $data[$k]['csusernum'];
            $result[] = $data[$k]['province'];
            $result[] = $data[$k]['szusernum'];
            $orders = $data[$k]['orders'];
            foreach ($orders as $key => $value) {
                if ($key == 0) {
                    $result[] = $orders[$key]['orderTotalCount'];
                    $result[] = $orders[$key]['orderTotalRatio'];
                    $result[] = round($orders[$key]['orderTotalRate'], 2).'%';
                } else {
                    $result[] = $orders[$key]['orderCount'];
                    $result[] = $orders[$key]['orderRatio'];
                    $result[] = round($orders[$key]['orderRate'], 2).'%';
                }
            }
            $results[] = $result;
        }
        if ($status == 5 && count($filterIndexs) > 1) {
            foreach ($titles as $k => $v) {
                if (!in_array($k.'', $filterIndexs)) {
                    unset($titles[$k]);
                }
            }
            foreach ($results as $key => $value) {
                foreach ($value as $k => $v) {
                    if (!in_array($k.'', $filterIndexs)) {
                        unset($results[$key][$k]);
                    }
                }
            }
        }
        $_savePath = ExportExcelTable($titles, $results, 'sheet', time(),'./Public/Uploads/GW/');
        $path = 'http://'.$_SERVER['SERVER_NAME'].substr($_savePath, 1, strlen($_savePath));
        $this -> ajaxReturn(['path' => $path], 'JSON');
    }

    public function getGwPersonnelInfo($msg, $orders, $orderopration, $gws, $sz, $city, $times, $rates, $tags, $istimes = false)
    {
        if ($msg == 'success') {
            //获取通过的订单
            $ordersList = $this -> getSuccessGwOrder($orders, $orderopration);
        } else if ($msg == 'overdue') {
            //获取逾期的订单
            $order_month_pay_db = M('order_month_pay');
            $order_month_pay = $order_month_pay_db -> select();
            $ordersList = $this -> getOverudeGwOrder($order_month_pay, $orderopration);
        }

        $data = [];$s = 0; $orderM = D('order');
        foreach ($gws as $k => $v) {
            $result = [];$z = 0;
            foreach ($ordersList as $key => $value) {
                //相等取出订单放入另外一个数组中
                if ($gws[$k]['usernum'] == $ordersList[$key]['usernum']) {
                    $result[$z] = $ordersList[$key];
                    $z++;
                }
            }

            //根据订单和时间获取过单数据
            if ($msg == 'success') {
                $result = $orderM -> getSuccessOrder($result, $times, $istimes);
            } else if ($msg == 'overdue') {
                $result = $orderM -> getOverdueOrder($result, $orders, $times, $istimes);
            }
            //取出城市经理的usernum和省总的usernum
            foreach ($sz as $key => $value) {
                if ($gws[$k]['pid'] == $sz[$key]['id']) {
                    $gws[$k]['csusernum'] = $sz[$key]['usernum'];
                }
                if ($sz[$key]['position'] == 4 && $gws[$k]['provinceid'] == $sz[$key]['provinceid']) {
                    $gws[$k]['szusernum'] = $sz[$key]['usernum'];
                }
            }
            //取出GW所属城市
            foreach ($city as $key => $value) {
                if ($gws[$k]['provinceid'] == $city[$key]['id']) {
                    $gws[$k]['province'] = $city[$key]['name'];
                }
                if ($gws[$k]['cityid'] == $city[$key]['id']) {
                    $gws[$k]['city'] = $city[$key]['name'];
                }
            }

            $ratesStatus = false;
            foreach ($result as $key => $value) {
                $r = $result[$key];
                if (count($rates) == 2 &&  $r['orderTotalRate'] >= $rates[0] && $r['orderTotalRate'] <= $rates[1]) {
                    $ratesStatus = true;
                }
                if (count($rates) == 2 &&  $r['orderRate'] >= $rates[0] && $r['orderRate'] <= $rates[1]) {
                    $ratesStatus = true;
                }
                if (count($tags) == 2 && $r['orderTotalRate'] >= $tags[0] && $r['orderTotalRate'] <= $tags[1]) {
                    $result[$key]['tag'] = true;
                }
                if (count($tags) == 2 &&  $r['orderRate'] >= $tags[0] && $r['orderRate'] <= $tags[1]) {
                    $result[$key]['tag'] = true;
                }
            }
            if (!$ratesStatus) continue;
            $res = [];
            $res['status'] = $gws[$k]['status'];
            $res['time'] = date('Y-m-d', $gws[$k]['insert_time']);
            $res['gwname'] = $gws[$k]['name'];
            $res['gwusernum'] = $gws[$k]['usernum'];
            $res['csusernum'] = $gws[$k]['csusernum'];
            $res['szusernum'] = $gws[$k]['szusernum'];
            $res['province'] = $gws[$k]['province'];
            $res['city'] = $gws[$k]['city'];
            $res['times'] = $times;
            $res['orders'] = $result;
            $data[$s] = $res;
            $s ++;
        }
        return $data;
    }

    public function findOrderInfo()
    {
        $id = I('request.id');
        $admin_db = M('admin');
        $order_db = M('order');

        $data = [];
        $orderM = D('order');
        $admin = $admin_db -> where(array('usernum' => $id)) -> find();
        if ($admin) {
            $data = $orderM -> findGwOrdersInfo($id);
        } else {
            $order = $order_db -> where(array('orderid'=>$id)) -> find();
            if ($order) {
                $data = $orderM -> findOrderIdOrderInfo($id);
            } else {
                $this -> ajaxReturn(['error'=> 1, 'msg' => []], 'JSON');
            }
        }
        session('orders', base64_encode(json_encode($data)));
        $this -> ajaxReturn(['error'=> '', 'msg' => $data], 'JSON');
    }

    public function selectOrderInfo()
    {
        $province = I('request.province');
        $city = I('request.city');
        $gwusernum = I('request.gwusernum');
        $waynum = I('request.waynum');
        $times = I('request.times');
        $orderStatus = I('request.orderStatus');
        $gwStatus= I('request.gwStatus');
        $wayStatus= I('request.wayStatus');

        $order_db = M('order');
        $city_db = M('city');
        $way_db = M('wayuser');
        $admin_db = M('admin');
        $user_db = M('user');
        $car_price_db = M('car_price');
        $order_month_pay_db = M('order_month_pay');
        $order_operation_db = M('order_operation');

        //条件组合查询GW人员
        $adminWhere = '';
        if ($gwusernum && $province && $city) {
            $adminWhere = "usernum="."'".$gwusernum."'"." and provinceid=".$province." and cityid=".$city;
        } else if ($province && $city) {
            $adminWhere = 'provinceid='.$province.' and cityid='.$city;
        } else if ($province) {
            $citys = $city_db -> field('id') -> where(array('pid' => $province)) -> select();
            $adminWhere = "cityid in (".implode(',', array_column($citys, 'id')).")";
        }
        if ($adminWhere && $gwStatus >= "0") $adminWhere .= " and status=".$gwStatus.' and test_sign <> 1';
        else if ($gwStatus >= "0" ) $adminWhere .= 'status='.$gwStatus.' and test_sign <> 1';
        else if ($adminWhere == '') $adminWhere = 'test_sign <> 1';
        //查询所有GW信息
        $admin = $admin_db -> where($adminWhere) -> select();
        //查询所有城市经理和省总
        $sz = $admin_db -> where('(position=3 or position=4) and test_sign <> 1') -> select();
        //条件组合查询渠道人员
        $user = false;
        if ($waynum) {
            $wayWhere = "waynum=".$waynum;
            if ($wayStatus >= "2")  $wayWhere .= " and status=".$wayStatus;
            $way = $way_db -> where($wayWhere) -> select();
            $user = $user_db -> where(array('waynum' => $waynum)) -> select();
            if (!$user) {
                $this -> ajaxReturn(['error'=> 1, 'msg' => []], 'JSON');
            }
            $usersId = "uid in (".implode(',', array_column($user, 'id')).")";
        } else {
            $wayWhere = "";
            if (($wayStatus >= "2") && $wayStatus != '')  $wayWhere .= "status=".$wayStatus;
            $way = $way_db -> where($wayWhere) -> select();
        }
        if (!$way) {
            $this -> ajaxReturn(['error'=> 1, 'msg' => []], 'JSON');
        }
        //条件组合查询订单
        $orderWhere = '';
        if (count($times) == 2) $orderWhere .= 'create_time >= '.$times[0].' and create_time <= '.$times[1];
        if (($orderStatus >= "0" || $orderStatus <= "0") && $orderStatus != '' && count($times) == 2) $orderWhere .= ' and status='.$orderStatus;
        else if (($orderStatus >= "0" || $orderStatus <= "0") && $orderStatus != '') $orderWhere .= 'status='.$orderStatus;
        if ($user && $orderWhere != '') $orderWhere .= ' and '.$usersId;
        else if ($user) $orderWhere .= $usersId;
        $orders = $order_db -> where($orderWhere) -> select();
        if (!$orders) {
            $this -> ajaxReturn(['error'=> 1, 'msg' => $order_db -> getLastSql()], 'JSON');
        }
        //查询订单分期
        $order_month_pay = $order_month_pay_db -> select();
        //查询订单操作记录
        $order_operation = $order_operation_db -> where(array('status' => 0)) -> select();
        //条件组合查询用户
        $where = "id in (".implode(',',array_column($orders, 'uid')).")";
        $users = $user_db -> where($where) -> select();
        //查询城市
        $city = $city_db -> select();
        //查询车辆价格
        $car_price = $car_price_db -> select();
        $data = $this -> orderList($orders, $order_operation, $order_month_pay, $users, $way, $car_price, $admin, $city, $sz);
        session('orders', base64_encode(json_encode($data)));
        $this -> ajaxReturn(['error'=> '', 'msg' => $data], 'JSON');
    }

    public function exportToExcelOrderList()
    {
        $status = I('request.status');
        $filterNames = I('request.filterNames');
        $filterIndexs = I('request.filterIndexs');
        $filterTag = I('request.filterTag');
        if ($status != 5) {
            $admin_db = M('admin');
            $order_db = M('order');
            $user_db = M('user');
            $wayuser_db = M('wayuser');
            $city_db = M('city');
            $car_price_db = M('car_price');
            $order_operation_db = M('order_operation');
            $order_month_pay_db = M('order_month_pay');
            $orderM = D('order');
            //获取导出时间
            $times = $this -> get_d_m($status);
            $time = strtotime($times[0].'-1');
            $arr = implode('-',$times[-1]);
            $time1 = strtotime($orderM -> get_y_m_d($arr[0], $arr[1]));
            $orderWhere = "create_time >=".$time.' and create_time <='.$time1;
            //查询所有GW 城市经理 省总
            $gw = $admin_db  -> where('position=1 test_sign <> 1') -> select();
            //查询所有城市经理 省总
            $sz = $admin_db -> where('(position=3 or position=4) test_sign <> 1') -> select();
            //查询订单信息
            $orders = $order_db -> where($orderWhere) -> select();
            //根据订单的uid查询用户
            $usersid = "id in (".implode(',', array_column($orders, 'uid')).")";
            $users = $user_db -> where($usersid) -> select();
            //根据用户的waynum查询渠道
            $wayusernums = "waynum in (".implode(',', array_column($users, 'waynum')).")";
            $wayuser = $wayuser_db -> where($wayusernums) -> select();
            //根据订单的orderid查询订单记录
            $orderids = "orderid in (".implode(',', array_column($orders, 'orderid')).")";
            $order_operation = $order_operation_db -> where($orderids.' and status=0') -> select();
            //根据订单的orderid查询订单分期
            $order_month_pay = $order_month_pay_db -> where($orderids) -> select();
            //查询所有城市
            $city = $city_db -> select();
            //根据订单的carnum查询车辆的价格
            $carnums = "carnum in (".implode(',', array_column($orders, 'carnum')).")";
            $carnums .= " and version in (".implode(',', array_column($orders, 'price_version')).")";
            $car_price = $car_price_db -> where($carnums) -> select();
            //获取数据
            $data = $this -> orderList($orders, $order_operation, $order_month_pay, $users, $wayuser, $car_price, $gw, $city, $sz);
        } else {
            $data = json_decode(base64_decode(session('orders')), true);
        }
        $titles = ['序号',
            '订单号',
            '订单创建时间',
            '订单状态',
            '逾期次数',
            '客户姓名',
            '联系方式',
            '渠道编号',
            '渠道状态',
            'GW姓名',
            'GW岗位号',
            '城市',
            'CS岗位号',
            '省份',
            'SZ岗位号',
            '订单总金额',
            '月供',
            '已还期数',
            '未还期数',
            '第1期还款时间',
            '第2期还款时间',
            '第3期还款时间',
            '第4期还款时间',
            '第5期还款时间',
            '第6期还款时间',
            '第7期还款时间',
            '第8期还款时间',
            '第9期还款时间',
            '第10期还款时间',
            '第11期还款时间',
            '第12期还款时间',
        ];
        $results = [];
        foreach ($data as $key => $value) {
            $orderStatus = '';
            switch ($data[$key]['status']) {
                case "0":
                    $orderStatus = '创建订单';
                    break;
                case "1":
                    $orderStatus = "风控已审";
                    break;
                case "2":
                    $orderStatus = "城市经理已审";
                    break;
                case "3":
                    $orderStatus = "用户已签约";
                    break;
                case "4":
                    $orderStatus = "确认收款";
                    break;
                case "5":
                    $orderStatus = "已上牌";
                    break;
                case "6":
                    $orderStatus = "交易完成";
                    break;
                case "-2":
                    $orderStatus = "暂拒订单";
                    break;
                case "-1":
                    $orderStatus = "被拒订单";
                    break;
            }
            $wayStatus = '';
            switch ($data[$key]['waystatus']) {
                case "0":
                    $wayStatus = "城市经理审核";
                    break;
                case "1":
                    $wayStatus = "风控审核";
                    break;
                case "2":
                    $wayStatus = "已完成";
                    break;
                case "3":
                    $wayStatus = "已关闭";
                    break;
                case "-1":
                    $wayStatus = "被拒绝";
                    break;
                case "-2":
                    $wayStatus = "被驳回";
                    break;
            }
            $result = [];
            $result[] = $key+1;
            $result[] = $data[$key]['orderid'];
            $result[] = $data[$key]['create_time'];
            $result[] = $orderStatus;
            $result[] = $data[$key]['overdue'];
            $result[] = $data[$key]['username'];
            $result[] = $data[$key]['tel'];
            $result[] = $data[$key]['waynum'];
            $result[] = $wayStatus;
            $result[] = $data[$key]['gwname'];
            $result[] = $data[$key]['gwusernum'];
            $result[] = $data[$key]['city'];
            $result[] = $data[$key]['csusernum'];
            $result[] = $data[$key]['province'];
            $result[] = $data[$key]['szusernum'];
            $result[] = $data[$key]['jdc_price'];
            $result[] = $data[$key]['money'];
            $result[] = $data[$key]['returnend'];
            $result[] = $data[$key]['notend'];
            $end_times = $data[$key]['end_times'];
            foreach ($end_times as $k => $v) {
                $result[] = $end_times[$k]['pay_time'];
            }
            $results[] = $result;
        }
        if ($status == 5 && count($filterIndexs) > 1) {
            foreach ($titles as $k => $v) {
                if (!in_array($k.'', $filterIndexs)) {
                    unset($titles[$k]);
                }
            }
            foreach ($results as $key => $value) {
                foreach ($value as $k => $v) {
                    if (!in_array($k.'', $filterIndexs)) {
                       unset($results[$key][$k]);
                    }
                }
            }
        }
        $_savePath = ExportExcelTable($titles, $results, 'sheet', time(),'./Public/Uploads/GW/');
        $path = 'http://'.$_SERVER['SERVER_NAME'].substr($_savePath, 1, strlen($_savePath));
        $this -> ajaxReturn(['path' => $path], 'JSON');
    }

    public function orderList($orders, $order_operation, $order_month_pay, $users, $way, $car_price, $admin, $city, $sz)
    {
        $data = [];
        //数据组合
        foreach ($orders as $key => $value) {
            //从订单记录取出GW岗位号
            $result = [];
            foreach ($order_operation as $k => $v) {
                if ($orders[$key]['orderid'] == $order_operation[$k]['orderid'] && $order_operation[$k]['status'] == 0) {
                    $orders[$key]['usernum'] = $order_operation[$k]['usernum'];
                    $result['gwusernum'] = $order_operation[$k]['usernum'];
                    $result['orderid'] = $orders[$key]['orderid'];
                    $result['create_time'] = date('Y-m-d',$orders[$key]['create_time']);
                    $result['status'] = $orders[$key]['status'];
                    break;
                }
            }
            //是否逾期
            $result['overdue'] = 0;
            //分期缴费次数
            $result['returnend'] = 0;
            //总分期
            $result['total'] = 0;
            $orderMonth = [];
            foreach ($order_month_pay as $k => $v) {
                //取出逾期
                if ($orders[$key]['orderid'] == $order_month_pay[$k]['orderid'] &&
                    $order_month_pay[$k]['overdue_status'] == 1) {
                    $result['overdue'] += 1;
                }
                //统计缴费次数
                if ($orders[$key]['orderid'] == $order_month_pay[$k]['orderid'] &&
                    $order_month_pay[$k]['status'] == 1) {
                    $result['returnend']++;
                }
                //统计总分期数和分期时间
                if ($orders[$key]['orderid'] == $order_month_pay[$k]['orderid']) {
                    $result['total']++;
                    $result['pay_time'] = date('Y-m-d',$order_month_pay[$k]['pay_time']);
                    $order_month_pay[$k]['pay_time'] = date('Y-m-d',$order_month_pay[$k]['pay_time']);
                    $orderMonth[] = $order_month_pay[$k];
                }
            }
            $result['notend'] = $result['total'] - $result['returnend'];
            //分期时间
            $result['end_times'] = $orderMonth;
            //取出用户信息
            foreach ($users as $k => $v) {
                if ($orders[$key]['uid'] == $users[$k]['id']) {
                    $result['username'] = $users[$k]['fullanme'];
                    $result['tel'] = $users[$k]['tel'];
                    $result['waynum'] = $users[$k]['waynum'];
                    $orders[$key]['waynum'] = $users[$k]['waynum'];
                    break;
                }
            }
            //取出渠道信息
            foreach ($way as $k => $v) {
                if ($orders[$key]['waynum'] == $way[$k]['waynum']) {
                    $result['waystatus'] = $way[$k]['status'];
                    break;
                }
            }
            //取出价格和月供
            foreach ($car_price as $k => $v) {
                if ($orders[$key]['carnum'] == $car_price[$k]['carnum'] &&
                    $orders[$key]['price_version'] == $car_price[$k]['version']) {
                    $result['jdc_price'] = $car_price[$k]['jdc_price'];
                    $result['money'] = $car_price[$k]['month_pay'];
                    break;
                }
            }
            $tag = false;
            foreach ($admin as $k => $v) {
                if ($admin[$k]['usernum'] == $result['gwusernum']) {
                    $tag = true;
                    $result['gwname'] = $admin[$k]['name'];
                    foreach ($sz as $j => $i) {
                        if ($admin[$k]['pid'] == $sz[$j]['id']) {
                            $result['csusernum'] = $sz[$j]['usernum'];
                        }
                        if ($sz[$j]['position'] == 4 && $admin[$k]['provinceid'] == $sz[$j]['provinceid']) {
                            $result['szusernum'] = $sz[$j]['usernum'];
                        }
                    }
                    foreach ($city as $i => $j) {
                        if ($admin[$k]['provinceid'] == $city[$i]['id']) {
                            $result['province'] = $city[$i]['name'];
                        }
                        if ($admin[$k]['cityid'] == $city[$i]['id']) {
                            $result['city'] = $city[$i]['name'];
                        }
                    }
                    break;
                }
            }
            if (!$tag) continue;
            $data[] = $result;
        }
        return $data;
    }

    public function get_d_m($status)
    {
        $time = [];
        if ($status == 1) {
            $y = date('Y', time());
            $y = $y - 1;
            for ($i = 1; $i<= 12; $i ++ ) {
                if ($i <= 9) {
                    $times[] = $y.'-0'.$i;
                } else {
                    $times[] = $y.'-'.$i;
                }
            }
        } else if ($status == 2) {
            $y = date('Y', time());
            $m = date('m', time());
            if ($m <= 3) {
                $times = [$y.'-'.'01', $y.'-'.'02', $y.'-'.'03'];
            } else if ($m >= 4 && $m <=6) {
                $times = [$y.'-'.'04', $y.'-'.'05', $y.'-'.'06'];
            } else if ($m >=7 && $m <= 9) {
                $times = [$y.'-'.'07', $y.'-'.'08', $y.'-'.'09'];
            } else if ($m >= 10 && $m <= 12) {
                $times = [$y.'-'.'10', $y.'-'.'11', $y.'-'.'12'];
            }
        } else if ($status == 3) {
            $y = date('Y', time());
            $m = date('m', time());
            $m = $m - 1;
            if ($m <= 0) {
                $y = $y - 1;
                $m = 12;
            }
            $times = [$y.'-'.$m];
        } else if ($status == 4) {
            $y = date('Y', time());
            $m = date('m', time());
            $times = [$y.'-'.$m];
        }
        return $times;
    }
}